package com.ksd.modules.course.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ksd.common.enums.DeletedEnums;
import com.ksd.common.enums.StatusEnums;
import com.ksd.common.po.BatchIdsPO;
import com.ksd.common.web.threadlocal.SystemIdThrealLocal;
import com.ksd.commons.BaseServiceImpl;
import com.ksd.modules.course.entity.AdminCourse;
import com.ksd.modules.course.mapper.AdminCourseMapper;
import com.ksd.modules.course.po.AdminCourseSavePO;
import com.ksd.modules.course.po.AdminCourseSearchPO;
import com.ksd.modules.course.service.IAdminCourseChapterService;
import com.ksd.modules.course.service.IAdminCourseLessonService;
import com.ksd.modules.course.service.IAdminCourseService;
import com.ksd.modules.course.vo.AdminCourseVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class AdminCourseServiceImpl extends BaseServiceImpl<AdminCourseMapper, AdminCourse> implements IAdminCourseService {


    @Autowired
    private IAdminCourseChapterService adminCourseChapterService;
    @Autowired
    private IAdminCourseLessonService adminCourseLessonService;

    /**
     * 查询列表
     * @param adminCourseSearchPO
     * @return
     */
    public Page<AdminCourseVo> findAdminCourses(AdminCourseSearchPO adminCourseSearchPO){
        Page<AdminCourse> page = new Page<>(adminCourseSearchPO.getPageNo(),adminCourseSearchPO.getPageSize());
        LambdaQueryWrapper<AdminCourse> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.select(AdminCourse.class, c -> !c.getColumn().equalsIgnoreCase("content"));
        lambdaQueryWrapper.eq(AdminCourse::getIsDeleted, DeletedEnums.UN_DELETED.getCode());
        lambdaQueryWrapper.eq(AdminCourse::getSystemId,SystemIdThrealLocal.get().getSystemId());
        lambdaQueryWrapper.eq(Objects.nonNull(adminCourseSearchPO.getStatus()), AdminCourse::getStatus,adminCourseSearchPO.getStatus());
        lambdaQueryWrapper.eq(Objects.nonNull(adminCourseSearchPO.getCoursetype()), AdminCourse::getCoursetype,adminCourseSearchPO.getCoursetype());
        lambdaQueryWrapper.eq(Objects.nonNull(adminCourseSearchPO.getNewFlag()), AdminCourse::getNewFlag,adminCourseSearchPO.getNewFlag());
        lambdaQueryWrapper.eq(Objects.nonNull(adminCourseSearchPO.getHotFlag()), AdminCourse::getHotFlag,adminCourseSearchPO.getHotFlag());
        lambdaQueryWrapper.eq(Objects.nonNull(adminCourseSearchPO.getPushFlag()), AdminCourse::getPushFlag,adminCourseSearchPO.getPushFlag());
        lambdaQueryWrapper.eq(Objects.nonNull(adminCourseSearchPO.getCategoryPid()), AdminCourse::getCategoryPid,adminCourseSearchPO.getCategoryPid());
        lambdaQueryWrapper.eq(Objects.nonNull(adminCourseSearchPO.getCategoryId()), AdminCourse::getCategoryId,adminCourseSearchPO.getCategoryId());
        lambdaQueryWrapper.eq(Objects.nonNull(adminCourseSearchPO.getCommentFlag()), AdminCourse::getCommentFlag,adminCourseSearchPO.getCommentFlag());
        lambdaQueryWrapper.eq(Objects.nonNull(adminCourseSearchPO.getMode()), AdminCourse::getMode,adminCourseSearchPO.getMode());
        lambdaQueryWrapper.eq(Objects.nonNull(adminCourseSearchPO.getVipFlag()), AdminCourse::getVipFlag,adminCourseSearchPO.getVipFlag());
        // 模糊匹配
        if(StringUtils.isNotEmpty(adminCourseSearchPO.getKeyword())){
            lambdaQueryWrapper.and(c -> c.like(
                            AdminCourse::getTitle,adminCourseSearchPO.getKeyword())
                    .or().like(AdminCourse::getNickname, adminCourseSearchPO.getKeyword())
                    .or().like(AdminCourse::getUuid, adminCourseSearchPO.getKeyword())
                    .or().like(AdminCourse::getTags, adminCourseSearchPO.getKeyword())
                    .or().like(AdminCourse::getCategoryPname, adminCourseSearchPO.getKeyword())
                    .or().like(AdminCourse::getCategoryName, adminCourseSearchPO.getKeyword())

            );
        }

        lambdaQueryWrapper.orderByDesc(AdminCourse::getCreateTime);
        Page<AdminCourse> adminCoursePage = this.page(page, lambdaQueryWrapper);
        Page<AdminCourseVo> adminCourseVoPage = tranferPageBo(adminCoursePage, AdminCourseVo.class);
        return adminCourseVoPage;
    }

    /**
     * 回收站
     * @param adminCourseSearchPO
     * @return
     */
    public Page<AdminCourseVo> findAdminCoursesRecyle(AdminCourseSearchPO adminCourseSearchPO){
        Page<AdminCourse> page = new Page<>(adminCourseSearchPO.getPageNo(),adminCourseSearchPO.getPageSize());
        LambdaQueryWrapper<AdminCourse> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.select(AdminCourse.class, c -> !c.getColumn().equalsIgnoreCase("content"));
        lambdaQueryWrapper.eq(AdminCourse::getIsDeleted, DeletedEnums.DELETED.getCode());
        lambdaQueryWrapper.eq(AdminCourse::getSystemId,SystemIdThrealLocal.get().getSystemId());
        lambdaQueryWrapper.eq(Objects.nonNull(adminCourseSearchPO.getStatus()), AdminCourse::getStatus,adminCourseSearchPO.getStatus());
        lambdaQueryWrapper.eq(Objects.nonNull(adminCourseSearchPO.getCoursetype()), AdminCourse::getCoursetype,adminCourseSearchPO.getCoursetype());
        lambdaQueryWrapper.eq(Objects.nonNull(adminCourseSearchPO.getNewFlag()), AdminCourse::getNewFlag,adminCourseSearchPO.getNewFlag());
        lambdaQueryWrapper.eq(Objects.nonNull(adminCourseSearchPO.getHotFlag()), AdminCourse::getHotFlag,adminCourseSearchPO.getHotFlag());
        lambdaQueryWrapper.eq(Objects.nonNull(adminCourseSearchPO.getPushFlag()), AdminCourse::getPushFlag,adminCourseSearchPO.getPushFlag());
        lambdaQueryWrapper.eq(Objects.nonNull(adminCourseSearchPO.getCategoryId()), AdminCourse::getCategoryId,adminCourseSearchPO.getCategoryId());
        lambdaQueryWrapper.eq(Objects.nonNull(adminCourseSearchPO.getCategoryPid()), AdminCourse::getCategoryPid,adminCourseSearchPO.getCategoryPid());
        lambdaQueryWrapper.eq(Objects.nonNull(adminCourseSearchPO.getCommentFlag()), AdminCourse::getCommentFlag,adminCourseSearchPO.getCommentFlag());
        lambdaQueryWrapper.eq(Objects.nonNull(adminCourseSearchPO.getMode()), AdminCourse::getMode,adminCourseSearchPO.getMode());
        lambdaQueryWrapper.eq(Objects.nonNull(adminCourseSearchPO.getVipFlag()), AdminCourse::getVipFlag,adminCourseSearchPO.getVipFlag());
        // 模糊匹配
        if(StringUtils.isNotEmpty(adminCourseSearchPO.getKeyword())){
            lambdaQueryWrapper.and(c -> c.like(
                            AdminCourse::getTitle,adminCourseSearchPO.getKeyword())
                    .or().like(AdminCourse::getNickname, adminCourseSearchPO.getKeyword())
                    .or().like(AdminCourse::getUuid, adminCourseSearchPO.getKeyword())
                    .or().like(AdminCourse::getTags, adminCourseSearchPO.getKeyword())
                    .or().like(AdminCourse::getCategoryPname, adminCourseSearchPO.getKeyword())
                    .or().like(AdminCourse::getCategoryName, adminCourseSearchPO.getKeyword())

            );
        }

        lambdaQueryWrapper.orderByDesc(AdminCourse::getCreateTime);
        Page<AdminCourse> adminCoursePage = this.page(page, lambdaQueryWrapper);
        Page<AdminCourseVo> adminCourseVoPage = tranferPageBo(adminCoursePage, AdminCourseVo.class);
        return adminCourseVoPage;
    }

    /**
     * 保存和更新
     * @param adminCourseSavePO
     * @return
     */
    @Transactional(rollbackFor=Exception.class)
    public AdminCourseVo saveUpdateAdminCourse(AdminCourseSavePO adminCourseSavePO){
        AdminCourse adminCourse = tranferBo(adminCourseSavePO, AdminCourse.class);
        adminCourse.setSystemId(SystemIdThrealLocal.get().getSystemId());
        adminCourse.setSystemName(SystemIdThrealLocal.get().getSystemName());
        boolean b = this.saveOrUpdate(adminCourse);
        AdminCourseVo adminCourseVo = tranferBo(adminCourse, AdminCourseVo.class);
        return adminCourseVo;
    }

    /**
     * 复制
     * @param opid
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean copyData(Long opid){
        AdminCourse  data= this.getById(opid);
        if(Objects.nonNull(data)){
            data.setId(null);
            data.setStatus(0);
            data.setCreateTime(LocalDateTime.now());
            data.setUpdateTime(LocalDateTime.now());
            data.setTitle(data.getTitle()+"[副本]");
            this.save(data);
        }
        return true;
    }

    /**
     * 根据ID获取明细
     * @param id
     * @return
     */
    public AdminCourseVo getAdminCourseById(Long id){
        AdminCourse adminCourse = this.getById(id);
        AdminCourseVo adminCourseVo = tranferBo(adminCourse, AdminCourseVo.class);
        return adminCourseVo;
    }

    /**
     * 单个逻辑删除
     * @param id
     * @return
     */
    @Transactional(rollbackFor=Exception.class)
    public Boolean deleteAdminCourseById(Long id){
        boolean b =  this.updateStatus(id, AdminCourse.Columns.IS_DELETED,1);
        return b;
    }

    /**
     * 单个恢复
     * @param id
     * @return
     */
    @Transactional(rollbackFor=Exception.class)
    public Boolean recoverByIdAdminCourse(Long id){
        boolean b =  this.updateStatus(id, AdminCourse.Columns.IS_DELETED,0);
        return b;
    }

    /**
     * 单个物理删除
     * @return
     */
    @Transactional(rollbackFor=Exception.class)
    public Boolean removeAdminCourseById(Long id){
        boolean b = this.removeById(id);
        if(b){
            adminCourseChapterService.removeByCourseId(id);
            adminCourseLessonService.removeByCourseId(id);
        }
        return b;
    }

    /**
     * 批量逻辑删除
     * @param batchIdsPO
     * @return
     */
    @Transactional(rollbackFor=Exception.class)
    public Boolean bacthDeletesAdminCourse(BatchIdsPO batchIdsPO){
        if (StringUtils.isEmpty(batchIdsPO.getIds())) {
            return false;
        }
        // 把文章分类进行恢复
        List<Long> ids = Arrays.stream(batchIdsPO.getIds().split(",")).map(Long::parseLong).collect(Collectors.toList());
        UpdateWrapper<AdminCourse> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("is_deleted", DeletedEnums.DELETED.getCode());
        updateWrapper.in("id", ids);
        boolean b = this.update(updateWrapper);
        return true;
    }

    /**
     * 批量恢复
     * @param batchIdsPO
     * @return
     */
    @Transactional(rollbackFor=Exception.class)
    public Boolean batchRecoversAdminCourse(BatchIdsPO batchIdsPO){
        if (StringUtils.isEmpty(batchIdsPO.getIds())) {
            return false;
        }
        // 把文章分类进行恢复
        List<Long> ids = Arrays.stream(batchIdsPO.getIds().split(",")).map(Long::parseLong).collect(Collectors.toList());
        UpdateWrapper<AdminCourse> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("is_deleted", DeletedEnums.UN_DELETED.getCode());
        updateWrapper.in("id", ids);
        boolean b = this.update(updateWrapper);
        return b;
    }

    /**
     * 批量物理删除
     * @param batchIdsPO
     * @return
     */
    @Transactional(rollbackFor=Exception.class)
    public Boolean batchRemovesAdminCourse(BatchIdsPO batchIdsPO){
        if (StringUtils.isEmpty(batchIdsPO.getIds())) {
            return false;
        }
        // 把文章分类进行恢复
        List<Long> ids = Arrays.stream(batchIdsPO.getIds().split(",")).map(Long::parseLong).collect(Collectors.toList());
        boolean b = this.removeByIds(ids);
        if(b){
            adminCourseChapterService.removeByCourseIds(ids);
            adminCourseLessonService.removeByCourseIds(ids);
        }
        return b;
    }


    /**
     * 修改状态
     * @param id
     * @param column
     * @param value
     * @return
     */
    @Override
    @Transactional(rollbackFor=Exception.class)
    public boolean updateStatus(Long id,String column,Integer value){
        boolean b = super.updateStatus(id,column,value);
        return b;
    }

    /**
     * 修改状态
     * @param id
     * @param column
     * @param value
     * @return
     */
    @Override
    public boolean updateStatusStr(Long id,String column,String value){
        boolean b = super.updateStatusStr(id,column,value);
        return b;
    }

    /**
     * 批量上架
     *
     * @param batchIdsPO
     * @return
     */
    @Override
    public Boolean batchDowns(BatchIdsPO batchIdsPO) {
        if (StringUtils.isEmpty(batchIdsPO.getIds())) {
            return false;
        }

        // 把文章进行恢复
        List<Long> ids = Arrays.stream(batchIdsPO.getIds().split(",")).map(Long::parseLong).collect(Collectors.toList());
        UpdateWrapper<AdminCourse> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("status", StatusEnums.UN_STATUS.getCode());
        updateWrapper.in("id", ids);
        return this.update(updateWrapper);
    }

    /**
     * 批量上架
     *
     * @param batchIdsPO
     * @return
     */
    @Override
    public Boolean batchUps(BatchIdsPO batchIdsPO) {
        if (StringUtils.isEmpty(batchIdsPO.getIds())) {
            return false;
        }

        // 把文章进行恢复
        List<Long> ids = Arrays.stream(batchIdsPO.getIds().split(",")).map(Long::parseLong).collect(Collectors.toList());
        UpdateWrapper<AdminCourse> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("status", StatusEnums.STATUS.getCode());
        updateWrapper.in("id", ids);
        return this.update(updateWrapper);
    }
}
